package cn.cm.config;

import cn.cm.entity.SysUser;
import cn.cm.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author shikundai
 * @date 2021/6/28
 * @time 16:13
 * @description: Shiro认证授权
 */
public class ShiroRealm extends AuthorizingRealm {
  @Autowired
  private UserService userService;
    /**
     * 描述：shiro授权
     * @author shikundai
     * @date 2021/6/28
     * @time 16:14
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 描述：shiro认证
     * @author shikundai
     * @date 2021/6/28
     * @time 16:13
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //从获需要取认证信息
        UsernamePasswordToken token= (UsernamePasswordToken) authenticationToken;
        //从数据库里面查询用户是否存在
        SysUser out=userService.getUserByname(token.getUsername());
        if (out==null){
            throw new RuntimeException("该用户不存在!");
        }
        //认证（Shiro会进行密码匹配）
        return new SimpleAuthenticationInfo(out,out.getPassword(),getName());
    }
}
